<template>
  <a-modal
    :width="1100"
    :visible="visible"
    title="修改计划收入"
    @cancel="onClose"
    ok-text="确定"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    @ok="onSubmit"
  >
    <section class="statistics">
      <a-row class="quantity" type="flex">
        <a-col class="text-center" :span="6">
          <div class="text">合同合计金额</div>
          <div class="number-width">
            ￥{{contractTotal}}
          </div>
        </a-col>
        <a-col class="text-center" :span="6">
          <div class="text">计划收入合计金额</div>
          <div class="number-width">
            ￥{{total}}
          </div>
        </a-col>
      </a-row>
    </section>
    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="false"
      rowKey="id"
      :loading="dataLoading"
      :scroll="{ x: 'max-content', y: 280}"
      class="mt-10"
    >
      <template #title>
        <span>计划收入（含税）</span>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.renderKey === 'monthRender'">
          <a-input-number
            v-if="text"
            class="w-100p"
            placeholder="请输入"
            v-model:value="text.receivable_with_tax"
            @change="handleToBeConfirmChange(text)"
            :min="0"
            :precision="2"
            @click.stop
          />
        </template>
      </template>
    </a-table>
  </a-modal>

</template>
<script>
import { defineComponent, reactive, toRefs, computed, watch } from "vue";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import _ from "lodash";

export default defineComponent({
  name: "EditPlanAmountModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    selectedRowKeys: {
      type: Array,
      default: () => [],
    }
  },
  components: {},
  setup(props, { emit }) {
    const state = reactive({
      submitLoading: false,
      dataSource: [],
      columns: [],
      dataLoading: false,
      changeData: {},
      contractTotal: 0,
      total: 0,
    });


    const onClose = () => {
      emit("handleCancel");
    };

    const onSubmit = () => {
      let submitData = _.cloneDeep(state.changeData);
      if (_.isEmpty(submitData)) {
        onClose()
      } else {
        state.submitLoading = true;
        const ids = Object.keys(submitData || {});
        let data = [];
        ids.forEach((id) => {
          data.push({
            id: id,
            amount: submitData[id],
          })
        })
        let params = {
          data,
          needMsg: true,
        };
        request.post("/org", "/incomeConfirm/submitModifyIncomeConfirm", params).then((res) => {
          message.success(res.msg || "设置成功!");
          emit("handleSuccess");
        }).finally(() => {
          state.submitLoading = false;
        });
      }
    };

    const getColumns = () => {
      let _columns = [
        {
          title: "年份",
          dataIndex: "year_name",
          key: "year_name",
          width: 80,
          fixed: "left",
        },
      ];
      for (let i = 1; i <= 12; i++) {
        _columns.push({
          title: `${i}月`,
          dataIndex: `month_${i}`,
          key: `month_${i}`,
          renderKey: 'monthRender',
          width: 120,
        });
      }
      state.columns = _columns;
    };

    const getTotal = () => {
      let total = 0;
      state.dataSource.forEach((item) => {
        const years = Object.keys(item || {});
        years.forEach((year) => {
          if (item[year]?.receivable_with_tax) {
            total = utils.countSum([Number(item[year].receivable_with_tax), total])
          }
        })
      });
      state.total = total;
    };

    const getDetail = () => {
      state.dataLoading = true;
      let data = props.selectedRowKeys.map((v) => {
        let info = v.split("&");
        return {
          contract_id: info[0],
          cost_type: info[1],
          owner_id: info[2],
        }
      })
      request
        .post("/org", "/incomeConfirm/modifyIncomeConfirmList", {data})
        .then((res) => {
          state.dataLoading = false;
          const years = Object.keys(res?.list || {});
          state.contractTotal = res?.total;
          let list = [];
          years.forEach((year) => {
            let obj = {
              year_name: year,
            }
            res.list[year].map((item) => {
              const arr = item?.y_m?.split("-");
              if (arr?.length > 1) {
                obj[`month_${Number(arr[1])}`] = {
                  ...item,
                };
              }
            })
            list.push(obj);
          })
          state.dataSource = list;
          getTotal();
        }).catch(() => {
        state.dataLoading = false;
      });
    };

    const handleToBeConfirmChange = (info) => {
      state.changeData[`${info.id}`] = info.receivable_with_tax;
      getTotal();
    };


    const init = () => {
      getColumns();
      getDetail();
    };

    const reset = () => {
      state.submitLoading = false;
      state.dataLoading = false;
      state.changeData = {};
      state.contractTotal = 0;
      state.total = 0;
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    return {
      ...toRefs(state),
      onClose,
      onSubmit,
      handleToBeConfirmChange,
    };
  },
});

</script>

<style lang="less" scoped>
:deep(.ant-alert-description) {
  font-size: 12px;
  p {
    margin-bottom: 6px;
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}
.statistics {
  margin-top: 10px;
  border: 1px solid #e6e5e5;
  .quantity {
    width: 100%;
    background-color: #fff;
    height: 100px;
    align-items: center;
    padding: 10px;
    .text-center {
      text-align: center;
      position: relative;
      .text {
        color: #8d8d8d;
        padding-bottom: 4px;
        font-size: 12px;
      }
      .number-width {
        color:#000;
        font-weight: 600;
        font-size: 18px;
        width: 100%;
        // 文字不折行
        overflow: hidden;
        word-break: break-all;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
  .text-center:not(:last-child):after {
    content: "";
    position: absolute;
    right: 0;
    top: 25%;
    height: 50%;
    border-left: 1px solid #e6e5e5;
  }
}
</style>
